﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using DevExpress.XtraEditors;
using DevExpress.XtraGrid;

using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;

namespace SZ
{
    public partial class IdentifyFrm : Form
    {
        #region 变量
        private AxMapControl m_mapControl;

        private IFeatureLayer pHighlightFeatureLayer = null;
        private ILayer pHighlightLayer = null;
        #endregion

        public IdentifyFrm(AxMapControl axMapControl)
        {
            InitializeComponent();
            m_mapControl = axMapControl;
        }

        public static IdentifyFrm Instance(AxMapControl pAxMapControl)
        {
            if (null == PublicVariablesClass.m_Identify)
            {
                PublicVariablesClass.m_Identify = new IdentifyFrm(pAxMapControl);
            }
            else
            {
                PublicVariablesClass.m_Identify.m_mapControl = pAxMapControl;
            }
            return PublicVariablesClass.m_Identify;
        }

        public void IdentifyFrm_Load(object sender, EventArgs e)
        {
            #region 初始化属性列表控件

            this.gridView1.Columns.Clear();

            DevExpress.XtraGrid.Columns.GridColumn colName = new DevExpress.XtraGrid.Columns.GridColumn();
            colName.FieldName = "FieldName";
            colName.VisibleIndex = 0;
            colName.Caption = "字段";
            colName.OptionsColumn.ShowCaption = true;
            colName.Width = 100;

            DevExpress.XtraGrid.Columns.GridColumn colValue = new DevExpress.XtraGrid.Columns.GridColumn();
            colValue.FieldName = "FieldValue";
            colValue.VisibleIndex = 1;
            colValue.Caption = "字段值";
            colValue.Width = 150;

            this.gridView1.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] { colName, colValue });

            DataTable m_DataTabel = new DataTable();
            m_DataTabel.Columns.Add("FieldName", typeof(string));
            m_DataTabel.Columns.Add("FieldValue", typeof(string));
            this.gridControl1.DataSource = m_DataTabel;

            #endregion
        }


        #region 增城代码

        public void GetInformation(IPoint iQueryPoint)
        {
            try
            {
                //取消高亮显示的要素
                IMap pMap = m_mapControl.Map;
                pMap.ClearSelection();

                this.treeView1.Nodes.Clear();
                this.layerComboBoxEdit.Properties.Items.Clear();

                //得到缓冲的范围值
                double pLength;
                pLength = ConvertPixelsToMapUnits(m_mapControl.ActiveView, 2);
                ITopologicalOperator pTopologic = iQueryPoint as ITopologicalOperator;
                IGeometry pGeometry = pTopologic.Buffer(pLength);

                for (int i = 0; i <= this.m_mapControl.LayerCount - 1; i++)
                {
                    ILayer pLayer = this.m_mapControl.get_Layer(i);
                    if (pLayer is IFeatureLayer && pLayer.Visible == true)
                    {
                        this.layerComboBoxEdit.Properties.Items.Add(pLayer.Name);
                        this.layerComboBoxEdit.Text = "";

                        #region 矢量图层
                        IFeatureLayer pFeatureLayer = pLayer as IFeatureLayer;
                        IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
                        ISpatialFilter pSpatialFilter = new SpatialFilterClass();
                        pSpatialFilter.Geometry = pGeometry;
                        pSpatialFilter.GeometryField = pFeatureClass.ShapeFieldName;
                        if (pFeatureClass.ShapeType == esriGeometryType.esriGeometryPoint)
                        {
                            pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                        }
                        if (pFeatureClass.ShapeType == esriGeometryType.esriGeometryPolyline)
                        {
                            pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                        }
                        if (pFeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                        {
                            pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                        }

                        IFeatureCursor pFeatureCursor = pFeatureClass.Search(pSpatialFilter, false);
                        IFeature pFeature = pFeatureCursor.NextFeature();
                        while (pFeature != null)
                        {
                            CreateQueryTreeList(pFeatureLayer, pFeature, this.treeView1);

                            #region 使选中的要素高亮显示

                            IFeatureSelection pFeatureSelection = pLayer as IFeatureSelection;
                            pFeatureSelection.SelectFeatures(pSpatialFilter as IQueryFilter, esriSelectionResultEnum.esriSelectionResultNew, false);
                            m_mapControl.ActiveView.Refresh();

                            #endregion

                            #region 在gridView中显示

                            DataTable DT = new DataTable();
                            DT.Columns.Add("FieldName", typeof(string));
                            DT.Columns.Add("FieldValue", typeof(string));

                            IFields pFields = pFeature.Fields;
                            for (int j = 0; j < pFeature.Fields.FieldCount; j++)
                            {
                                IField pField = pFields.get_Field(j);
                                string fieldName = pField.Name;

                                IRow pRow = pFeature as IRow;
                                string fieldValue = pRow.get_Value(j).ToString();

                                DataRow m_row = DT.Rows.Add();
                                m_row["FieldName"] = fieldName;
                                m_row["FieldValue"] = fieldValue;

                            }
                            this.gridView1.GridControl.DataSource = DT;
                            pFeature = pFeatureCursor.NextFeature();

                            #endregion
                        }

                        this.treeView1.ExpandAll();

                        System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor);
                        pFeatureCursor = null;
                        GC.Collect();
                        #endregion

                    }
                }
            }
            catch
            {

            }
        }

        public void GetInformation(IEnvelope pEnvelop)
        {
            //取消高亮显示的要素
            IMap pMap = m_mapControl.Map;
            pMap.ClearSelection();

            this.treeView1.Nodes.Clear();
            this.layerComboBoxEdit.Properties.Items.Clear();

            //得到框选的范围
            ISpatialFilter pSpatialFilter = new SpatialFilterClass();
            pSpatialFilter.Geometry = pEnvelop;
            for (int i = 0; i < m_mapControl.LayerCount; i++)
            {
                ILayer pLayer = m_mapControl.get_Layer(i);
                if (pLayer is IFeatureLayer)
                {
                    IFeatureLayer pFeatureLayer = pLayer as IFeatureLayer;
                    IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
                    string pShapeFieldName = pFeatureClass.ShapeFieldName;
                    pSpatialFilter.GeometryField = pShapeFieldName;
                    pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;

                    IFeatureCursor pFeatureCursor = pFeatureClass.Search(pSpatialFilter, false);
                    IFeature pFeature = pFeatureCursor.NextFeature();
                    while (pFeature != null)
                    {
                        CreateQueryTreeList(pFeatureLayer, pFeature, this.treeView1);

                        #region 使选中的要素高亮显示

                        IFeatureSelection pFeatureSelection = pLayer as IFeatureSelection;
                        pFeatureSelection.SelectFeatures(pSpatialFilter as IQueryFilter, esriSelectionResultEnum.esriSelectionResultNew, false);
                        m_mapControl.ActiveView.Refresh();

                        #endregion

                        #region 在gridView中显示

                        DataTable DT = new DataTable();
                        DT.Columns.Add("FieldName", typeof(string));
                        DT.Columns.Add("FieldValue", typeof(string));

                        IFields pFields = pFeature.Fields;
                        for (int j = 0; j < pFeature.Fields.FieldCount; j++)
                        {
                            IField pField = pFields.get_Field(j);
                            string fieldName = pField.Name;

                            IRow pRow = pFeature as IRow;
                            string fieldValue = pRow.get_Value(j).ToString();

                            DataRow m_row = DT.Rows.Add();
                            m_row["FieldName"] = fieldName;
                            m_row["FieldValue"] = fieldValue;

                        }
                        this.gridView1.GridControl.DataSource = DT;
                        pFeature = pFeatureCursor.NextFeature();

                        #endregion
                    }

                }
            }

        }

        #endregion

        //将像素单位转换为地图单位
        public double ConvertPixelsToMapUnits(IActiveView pActiveView, double pixelUnits)
        {
            double realWorldDisplayExtent;
            int pixelExtent;
            double sizeOfOnePixel;

            pixelExtent = pActiveView.ScreenDisplay.DisplayTransformation.get_DeviceFrame().right - pActiveView.ScreenDisplay.DisplayTransformation.get_DeviceFrame().left;
            realWorldDisplayExtent = pActiveView.ScreenDisplay.DisplayTransformation.VisibleBounds.Width;
            sizeOfOnePixel = realWorldDisplayExtent / pixelExtent;

            return pixelUnits * sizeOfOnePixel;
        }

        //创建查询目录树
        public void CreateQueryTreeList(IFeatureLayer pFeatureLayer, IFeature pFeature, TreeView treeView)
        {
            try
            {
                TreeNode treeNode = new TreeNode();
                if (treeView.Nodes.ContainsKey(pFeatureLayer.Name))
                {
                    treeNode = treeView.Nodes[pFeatureLayer.Name]; //pFeatureLayer.name可以作为索引值？

                }
                else
                {
                    treeNode = treeView.Nodes.Add(pFeatureLayer.Name, pFeatureLayer.Name);
                }

                int indexFieldId = 0;
                for (int j = 0; j < pFeature.Fields.FieldCount; j++)
                {
                    if (pFeature.Fields.get_Field(j).Type == esriFieldType.esriFieldTypeOID)
                    {
                        indexFieldId = j;
                        break;
                    }
                }
                string Id = pFeature.get_Value(indexFieldId).ToString().Trim();
                TreeNode m_treeNode = treeNode.Nodes.Add(Id, Id);
                m_treeNode.Tag = pFeature;
            }
            catch
            {

            }
        }

        //根据IFeature在mapControl中查找
        private void DisplayFeature(IFeature pFeature)
        {
            DataTable DT = this.gridControl1.DataSource as DataTable;

            if (DT == null)
            {
                DT = new DataTable();
                DT.Columns.Add("FieldName", typeof(string));
                DT.Columns.Add("FieldValue", typeof(string));
                this.gridControl1.DataSource = DT;

            }
            else
            {
                DT.Rows.Clear();
            }

            DataRow dataRow = null;
            IField pField = null;
            int index = 0;
            for (int i = 0; i < pFeature.Fields.FieldCount; i++)
            {
                pField = pFeature.Fields.get_Field(i);
                //排除几何字段
                if (pField.Type != esriFieldType.esriFieldTypeGeometry)
                {
                    dataRow = DT.Rows.Add();
                    dataRow["FieldName"] = pField.Name;

                    index = pFeature.Fields.FindField(pField.Name);

                    dataRow["FieldValue"] = pFeature.get_Value(index);
                }
            }
        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.Nodes.Count == 0)
            {
                IMap pMap = m_mapControl.Map;
                pMap.ClearSelection(); //取消前面的操作的高亮显示
                IFeature pFeature = e.Node.Tag as IFeature;
                DisplayFeature(pFeature);
                //高亮显示
                string LayerName = e.Node.Parent.Name.ToString();
                for (int i = 0; i < m_mapControl.LayerCount; i++)
                {
                    string name = m_mapControl.get_Layer(i).Name;
                    if (name == LayerName)
                    {
                        pHighlightLayer = m_mapControl.get_Layer(i);
                        pHighlightFeatureLayer = pHighlightLayer as IFeatureLayer;
                        break;
                    }
                }
                string name1 = pFeature.get_Value(0).ToString();
                pMap.SelectFeature(pHighlightLayer, pFeature);
                m_mapControl.ActiveView.Refresh();

            }
        }

        private void layerComboBoxEdit_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (TreeNode node in treeView1.Nodes)
            {
                if (node.Text != layerComboBoxEdit.Text)
                {
                    node.Remove();

                }
                layerComboBoxEdit.Properties.Items.Clear();
                //layerComboBoxEdit.Properties.Items.Add(node.Text);
                layerComboBoxEdit.Text = node.Text;

                //使符合条件的要素高亮显示

                //IFeatureSelection pFeatureSelection = m_mapControl.Map.FeatureSelection as IFeatureSelection;
                //IQueryFilter pQueryFilter = new QueryFilterClass();
                //pQueryFilter .WhereClause = 
            }
        }

        private void IdentifyFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            PublicVariablesClass.m_Identify = null;
        }


    }
}
